import React, {useEffect, useState} from "react"
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  TextInput,
  ScrollView,
  StatusBar,
  Modal,
  TouchableWithoutFeedback,
  Alert,
  PermissionsAndroid,
  Platform,

  // ActivityIndicator,
} from "react-native"
import {SafeAreaView} from "react-native-safe-area-context"
import {
  UserIcon,
  CalendarIcon,
  LocationIcon,
  ArrowDownIcon,
} from "../../assets/icons"
import {
  AVATAR_MALE,
  AVATAR_FEMALE,
  AVATAR_MALE_SELECTED,
  AVATAR_FEMALE_SELECTED,
} from "../../assets/avatars"
import {Picker} from "@react-native-picker/picker"
import {useCityData, useDate, useLocation, useShowToast} from "../../hooks"
import {completeDate} from "../../utils/common"
import {requestPermission} from "../../utils/permission"
import {
  Asset,
  CameraOptions,
  launchCamera,
  launchImageLibrary,
  MediaType,
} from "react-native-image-picker"
import {UserInfoParams} from "types/user"
import {getUserInfoAPI, saveUserAPI, uploadAvatarAPI} from "../../api"
import {useTHNavigation} from "../../utils/navigation"

// 用户数据接口定义
interface UserData {
  nickname: string
  birthday: string
  location: string
  avatar: string | null
  avatarIndex: number | null
  customAvatar?: string
}

// 临时用户数据
const USER_DATA: UserData = {
  nickname: "",
  birthday: "",
  location: "广州市",
  avatar: null,
  avatarIndex: null,
}

const UserInfo = () => {
  const [currentAsset, setCurrentAsset] = useState<Asset>({}) // 当前选择头像
  const [userData, setUserData] = useState<UserData>(USER_DATA)
  const [showBirthDay, setShowBirthDay] = useState(false) // 控制生日弹层
  const [showCity, setShowCity] = useState(false) // 控制生日弹层
  const {YEARS, MONTHS, DAYS} = useDate() // 使用年月日数据
  const {currentAddress, currentLocation} = useLocation()
  const navigation = useTHNavigation()
  const showToast = useShowToast()
  const [selectedDate, setSelectedDate] = useState({
    year: new Date().getFullYear() - 25,
    month: 1,
    day: 1,
  })
  const {
    provinceList,
    cityList,
    areaList,
    currentArea,
    currentCity,
    currentProvince,
    changeArea,
    changeProvince,
    changeCity,
  } = useCityData() // 使用城市数据
  useEffect(() => {
    getUserInfo()
  }, [])
  const getUserInfo = async () => {
    const res = await getUserInfoAPI()
    setUserData({
      ...userData,
      nickname: res.nick_name,
      avatar: res.header,
      customAvatar: res.header,
      birthday: res.birthday,
      location: res.city || "",
    })
  }
  // 模拟头像选择
  const handleSelectAvatar = () => {
    console.log("选择头像")
    Alert.alert(
      "设置头像",
      "请选择头像获取方式",
      [
        {
          text: "取消",
          style: "cancel",
        },
        {
          text: "拍照",
          onPress: () => {
            takePhoto()
          },
        },
        {
          text: "从相册选择",
          onPress: () => {
            openGallery()
          },
        },
      ],
      {cancelable: true},
    )
    // 实际应用中需要调用图片选择库和上传功能
  }
  // 拍照
  const takePhoto = async () => {
    await requestPermission(PermissionsAndroid.PERMISSIONS.CAMERA)
    const options: CameraOptions = {
      mediaType: "photo" as MediaType,
      quality: 0.8,
      includeBase64: false,
      saveToPhotos: true,
      cameraType: "back",
    }
    const res = await launchCamera(options)
    if (res.assets?.length) {
      updateUserData("customAvatar", res.assets[0].uri)
      setCurrentAsset(res.assets[0])
    }
  }
  // 打开相册

  const openGallery = async () => {
    // 33版本以上直接读取图片
    if (parseInt(`${Platform.Version}`, 10) >= 33) {
      requestPermission(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES)
        .then(() => {
          return launchImageLibrary({
            mediaType: "photo" as MediaType,
            quality: 0.8,
            includeBase64: false,
            selectionLimit: 1,
          })
        })
        .then(res => {
          if (res?.assets?.length) {
            updateUserData("customAvatar", res.assets[0].uri)
            setCurrentAsset(res.assets[0])
          }
        })
        .catch(() => {
          showToast("您没有读取相册的权限")
        })
    } else {
      requestPermission(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE)
        .then(() => {
          return launchImageLibrary({
            mediaType: "photo" as MediaType,
            quality: 0.8,
            includeBase64: false,
            selectionLimit: 1,
          })
        })
        .then(res => {
          if (res?.assets?.length) {
            updateUserData("customAvatar", res.assets[0].uri)
            setCurrentAsset(res.assets[0])
          }
        })
        .catch(() => {
          showToast("您没有读取相册的权限")
        })
    }
  }
  // 更新用户信息
  const updateUserData = (key: keyof UserData, value: any) => {
    setUserData({
      ...userData,
      [key]: value,
    })
  }
  const selectCity = () => {
    setShowCity(true)
  }
  // 选择生日
  const selectBirthDay = () => {
    setShowBirthDay(true) // 显示生日弹层
  }
  const renderYearItem = () => {
    return YEARS.map(item => (
      <Picker.Item key={item} label={`${item}年`} value={item} />
    ))
  }
  const renderMonthItem = () => {
    return MONTHS.map(month => (
      <Picker.Item key={month} label={`${month}月`} value={month} />
    ))
  }
  const renderDayItem = () => {
    return DAYS.map(day => (
      <Picker.Item key={day} label={`${day}日`} value={day} />
    ))
  }
  // 渲染省数据
  const renderProvinceItem = () => {
    return provinceList.map(province => (
      <Picker.Item key={province} label={`${province}`} value={province} />
    ))
  }
  // 渲染城市数据
  const renderCityItem = () => {
    return cityList.map(city => (
      <Picker.Item key={city} label={`${city}`} value={city} />
    ))
  }
  // 渲染区域数据
  const renderAreaItem = () => {
    return areaList.map(area => (
      <Picker.Item key={area} label={`${area}`} value={area} />
    ))
  }

  // 选择生日数据
  const confirmBirthDay = () => {
    updateUserData(
      "birthday",
      `${selectedDate.year}-${completeDate(selectedDate.month)}-${completeDate(
        selectedDate.day,
      )}`,
    )
    setShowBirthDay(false)
  }

  // 日期滚轮选择器
  const renderDatePicker = () => {
    return (
      <Modal
        transparent
        animationType="fade"
        visible={showBirthDay}
        onRequestClose={() => setShowBirthDay(false)}>
        <TouchableWithoutFeedback onPress={() => setShowBirthDay(false)}>
          <View style={styles.modalOverlay}>
            <TouchableWithoutFeedback onPress={e => e.stopPropagation()}>
              <View style={styles.datePickerContainer}>
                <View style={styles.datePickerHeader}>
                  <TouchableOpacity onPress={() => setShowBirthDay(false)}>
                    <Text style={styles.datePickerCancelText}>取消</Text>
                  </TouchableOpacity>
                  <Text style={styles.datePickerTitle}>选择生日</Text>
                  <TouchableOpacity onPress={confirmBirthDay}>
                    <Text style={styles.datePickerConfirmText}>确定</Text>
                  </TouchableOpacity>
                </View>

                <View style={styles.datePickerContent}>
                  {/* 年份选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      selectedValue={selectedDate.year.toString()}
                      onValueChange={value =>
                        setSelectedDate({
                          ...selectedDate,
                          year: ~~value,
                        })
                      }>
                      {renderYearItem()}
                    </Picker>
                  </View>

                  {/* 月份选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      selectedValue={selectedDate.month.toString()}
                      onValueChange={value =>
                        setSelectedDate({
                          ...selectedDate,
                          month: ~~value,
                        })
                      }>
                      {renderMonthItem()}
                    </Picker>
                  </View>

                  {/* 日期选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      selectedValue={selectedDate.day.toString()}
                      onValueChange={value =>
                        setSelectedDate({
                          ...selectedDate,
                          day: ~~value,
                        })
                      }>
                      {renderDayItem()}
                    </Picker>
                  </View>
                </View>
              </View>
            </TouchableWithoutFeedback>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    )
  }
  // 确认城市
  const confirmCity = () => {
    updateUserData(
      "location",
      `${currentProvince}-${currentCity}-${currentArea}`,
    )
    setShowCity(false)
  }
  // 城市选择器
  const renderCityPicker = () => {
    return (
      <Modal
        transparent
        visible={showCity}
        animationType="fade"
        onRequestClose={() => setShowCity(false)}>
        <TouchableWithoutFeedback onPress={() => setShowCity(false)}>
          <View style={styles.modalOverlay}>
            <TouchableWithoutFeedback onPress={e => e.stopPropagation()}>
              <View style={styles.datePickerContainer}>
                <View style={styles.datePickerHeader}>
                  <TouchableOpacity onPress={() => setShowCity(false)}>
                    <Text style={styles.datePickerCancelText}>取消</Text>
                  </TouchableOpacity>
                  <Text style={styles.datePickerTitle}>选择城市</Text>
                  <TouchableOpacity onPress={confirmCity}>
                    <Text style={styles.datePickerConfirmText}>确定</Text>
                  </TouchableOpacity>
                </View>

                <View style={styles.datePickerContent}>
                  {/* 省份选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      onValueChange={(value: string) => changeProvince(value)}
                      selectedValue={currentProvince}>
                      {renderProvinceItem()}
                    </Picker>
                  </View>

                  {/* 城市选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      selectedValue={currentCity}
                      onValueChange={(value: string) => changeCity(value)}>
                      {renderCityItem()}
                    </Picker>
                  </View>

                  {/* 区县选择 */}
                  <View style={styles.pickerWrapper}>
                    <Picker
                      style={styles.picker}
                      itemStyle={styles.pickerItem}
                      selectedValue={currentArea}
                      onValueChange={(value: string) => changeArea(value)}>
                      {renderAreaItem()}
                    </Picker>
                  </View>
                </View>
              </View>
            </TouchableWithoutFeedback>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    )
  }
  // 提交用户资料
  const saveUser = async () => {
    let user: UserInfoParams = {
      city: userData.location,
      birthday: userData.birthday,
      gender: userData.avatarIndex === 0 ? "男" : "女",
      header: "",
      lat: "0",
      lng: "0",
      nickname: userData.nickname,
      address: userData.location,
    }
    if (currentAsset.uri) {
      const data = new FormData()
      const source = {
        uri: currentAsset.uri,
        type: currentAsset.type,
        name: currentAsset.fileName,
      }
      data.append("headPhoto", source)
      const res = await uploadAvatarAPI(data)
      user.header = res.headImgPath // 设置头像
      setCurrentAsset({}) // 重新置空数据
    }
    // 赋值经纬度和位置
    user.address = currentAddress
    user.lat = currentLocation.latitude.toString()
    user.lng = currentLocation.longitude.toString()

    if (!user.nickname || !user.birthday) {
      showToast("昵称生日和当前位置不能为空")
      return
    }
    await saveUserAPI(user)
    navigation.push("Tabbar")
    showToast("保存用户信息成功")
  }
  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar backgroundColor="#fff" barStyle="dark-content" />
      <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>填写资料</Text>
          <Text style={styles.headerSubtitle}>提升我的魅力</Text>
        </View>

        <View style={styles.avatarContainer}>
          {/* 头像选择区域 */}
          <View style={styles.avatarOptions}>
            {userData.customAvatar ? (
              <View style={styles.customAvatarContainer}>
                <Image
                  source={{uri: userData.customAvatar}}
                  style={styles.customAvatar}
                  resizeMode="cover"
                />
              </View>
            ) : (
              <>
                <TouchableOpacity
                  style={styles.avatarOption}
                  onPress={() => updateUserData("avatarIndex", 0)}>
                  <Image
                    source={
                      userData.avatarIndex === 0
                        ? AVATAR_MALE_SELECTED
                        : AVATAR_MALE
                    }
                    style={styles.avatarPreview}
                    resizeMode="contain"
                  />
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.avatarOption}
                  onPress={() => updateUserData("avatarIndex", 1)}>
                  <Image
                    source={
                      userData.avatarIndex === 1
                        ? AVATAR_FEMALE_SELECTED
                        : AVATAR_FEMALE
                    }
                    style={styles.avatarPreview}
                    resizeMode="contain"
                  />
                </TouchableOpacity>
              </>
            )}
          </View>
        </View>

        {/* 信息表单 */}
        <View style={styles.formContainer}>
          <View style={styles.formItem}>
            <View style={styles.iconContainer}>
              <UserIcon size={18} color="#666" />
            </View>
            <TextInput
              style={styles.formInput}
              placeholder="昵称设置"
              value={userData.nickname}
              onChangeText={text => updateUserData("nickname", text)}
            />
          </View>

          <TouchableOpacity style={styles.formItem} onPress={selectBirthDay}>
            <View style={styles.iconContainer}>
              <CalendarIcon size={18} color="#666" />
            </View>
            <View style={styles.formValueContainer}>
              <Text style={styles.formValue}>
                {userData.birthday || "请选择生日"}
              </Text>
              <ArrowDownIcon size={16} color="#999" />
            </View>
          </TouchableOpacity>

          <TouchableOpacity style={styles.formItem} onPress={selectCity}>
            <View style={styles.iconContainer}>
              <LocationIcon size={18} color="#666" />
            </View>
            <View style={styles.formValueContainer}>
              <Text style={styles.formValue}>{userData.location}</Text>
              <ArrowDownIcon size={16} color="#999" />
            </View>
          </TouchableOpacity>
        </View>

        {/* 头像上传按钮 */}
        <TouchableOpacity
          style={styles.avatarButton}
          onPress={handleSelectAvatar}>
          <Text style={styles.avatarButtonText}>设置头像</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.avatarButton} onPress={saveUser}>
          <Text style={styles.avatarButtonText}>提交资料</Text>
        </TouchableOpacity>
      </ScrollView>
      {/* 渲染生日弹层 */}
      {renderDatePicker()}
      {/* 渲染城市弹层 */}
      {renderCityPicker()}
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "#fff",
  },
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  header: {
    paddingHorizontal: 20,
    paddingTop: 20,
    paddingBottom: 10,
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#333",
  },
  headerSubtitle: {
    fontSize: 16,
    color: "#666",
    marginTop: 4,
  },
  avatarContainer: {
    alignItems: "center",
    marginVertical: 20,
  },
  avatarOptions: {
    flexDirection: "row",
    justifyContent: "center",
    marginVertical: 20,
  },
  avatarOption: {
    marginHorizontal: 10,
    borderRadius: 45,
    padding: 4,
  },
  avatarPreview: {
    width: 80,
    height: 80,
    borderRadius: 40,
  },
  formContainer: {
    paddingHorizontal: 20,
  },
  formItem: {
    flexDirection: "row",
    alignItems: "center",
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
    paddingVertical: 15,
  },
  iconContainer: {
    width: 26,
  },
  formInput: {
    flex: 1,
    fontSize: 16,
    color: "#333",
    padding: 0,
  },
  formValueContainer: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  formValue: {
    fontSize: 16,
    color: "#333",
  },
  placeholder: {
    color: "#999",
  },
  formArrow: {
    fontSize: 16,
    color: "#999",
  },
  avatarButton: {
    marginTop: 40,
    marginBottom: 20,
    marginHorizontal: 20,
    paddingVertical: 15,
    borderRadius: 30,
    alignItems: "center",
    backgroundColor: "#8a56ac",
    // 在RN中实现渐变需要特殊处理，通常使用第三方库
    // 在iOS的完整实现中可使用react-native-linear-gradient
    elevation: 2, // Android阴影
    shadowColor: "#000", // iOS阴影
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  avatarButtonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "bold",
  },
  // 选择器通用样式
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    justifyContent: "flex-end",
  },
  datePickerContainer: {
    backgroundColor: "#fff",
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    paddingBottom: 20,
  },
  datePickerHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
  },
  datePickerTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "#333",
  },
  datePickerCancelText: {
    fontSize: 15,
    color: "#666",
  },
  datePickerConfirmText: {
    fontSize: 15,
    color: "#8a56ac",
    fontWeight: "bold",
  },
  datePickerContent: {
    flexDirection: "row",
    height: 240,
  },
  // Picker样式
  pickerWrapper: {
    flex: 1,
    height: 240,
  },
  picker: {
    flex: 1,
  },
  pickerItem: {
    fontSize: 16,
    color: "#333",
  },
  // 加载状态容器
  loadingContainer: {
    height: 240,
    justifyContent: "center",
    alignItems: "center",
  },
  customAvatarPreview: {
    borderWidth: 2,
    borderColor: "#8a56ac",
    overflow: "hidden",
  },
  selectedAvatarOption: {
    borderWidth: 3,
    borderColor: "#8a56ac",
    backgroundColor: "rgba(138, 86, 172, 0.1)",
    borderRadius: 45,
  },
  customAvatarContainer: {
    width: 100,
    height: 100,
    borderRadius: 50,
    overflow: "hidden",
    borderWidth: 2,
    borderColor: "#8a56ac",
  },
  customAvatar: {
    width: "100%",
    height: "100%",
  },
})
export default UserInfo
